package com.personal.ifanya.presentation.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.personal.ifanya.application.service.VoteService;
import com.personal.ifanya.presentation.model.AsynResult;
import com.personal.ifanya.presentation.model.SessionBox;

@Controller
@RequestMapping("/vote")
@SessionAttributes(value={"sessionBox"})
public class VoteController {

	
	@Autowired
	private VoteService voteService;
	
	@RequestMapping(value="/result",produces = "application/json; charset=utf-8")
	@ResponseBody
	public String getResult(@ModelAttribute("sessionBox") SessionBox sessionBox,
			HttpServletResponse response)
	{ 
		return JSON.toJSONString(voteService.getAll());
	}
	
	
	@RequestMapping(value="/vote",produces = "application/json; charset=utf-8")
	@ResponseBody
	public String vote(@ModelAttribute("sessionBox") SessionBox sessionBox, @RequestParam("whichvote") int whichvote, @RequestParam("value") int value, 
			HttpServletResponse response)
	{ 
		AsynResult<Boolean> result = new AsynResult<Boolean>();
		if(!sessionBox.isVoted())
		{
			if(voteService.addVote(whichvote, value))
			{
				result.setAll(true, true, AsynResult.Error.NONE);
				sessionBox.setVoted(true);
			}
			else
			{
				result.setAll(true, false, AsynResult.Error.FAILED);
			} 
		}
		else
		{
			result.setAll(true, false, AsynResult.Error.FAILED, "您已经投过票了，请于1小时候再投。");
		}
		return JSON.toJSONString(result);
	}
	
	
}
